package ntd.util.frame.action.ai;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.tool.ToolAiUserSites;

import java.sql.SQLException;
import java.util.Comparator;
import java.util.List;

public class ActionAiStatisticsSite extends ActionAbs {

    @Override
    public ActionInfo info() {
        return new ActionInfo("AI统计-按基站统计", "ai-statistics-site", new ActionAiStatisticsSite());
    }

    @Override
    public ActionOutBo handle() {
        String mn = actionInBo.getParamStr("mn");
        String aiModeType = actionInBo.getParamStr("aiModeType");

        //数据库
        Db use = Db.use(FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c"));

        String whereSql = "where 1 = 1";
        if (StrUtil.isNotBlank(mn)) {
            if (!ToolAiUserSites.IsExistMn(mn)){
                throw new ComException("没有该站点的权限，请联系管理员！");
            }
            whereSql += StrUtil.format(" and siteMn = '{}'", mn);
        }
        if (StrUtil.isNotBlank(aiModeType)) {
            whereSql += StrUtil.format(" and ai_mode_type = '{}'", aiModeType);
        }

        String sql = "select count(*) as num, siteMn from airesult " + whereSql + " group by siteMn";

        try {
            List<Entity> entities = use.query(sql);
            return new ActionOutBo(CollectionUtil.reverse(CollectionUtil.sort(entities, Comparator.comparingInt(o2 -> o2.getInt("num")))));
        } catch (SQLException e) {
            StaticLog.error(e, "[AI][分类查询][{}]失败...");
            throw new ComException("分类查询失败，请稍后重试...");
        }
    }
}
